const grpc = require('@grpc/grpc-js')
const message_proto = require('./proto')
const const_module = require('./const')
const { v4: uuidv4 } = require('uuid');
const emailModule = require('./email');
const redis_module = require('./redis')

function shortenUUID(uuid) {
    // hash
    const hashValue = uuid.split('-').reduce((acc, part) => acc + parseInt(part, 16), 0) % 1000000;
    return hashValue.toString().padStart(6, '0');
}

async function GetVerifyCode(call, callback) {
    console.log("VerifyPack {\n   email is:", call.request.email)
    try{
        let query_res = await redis_module.GetRedis(const_module.code_prefix + call.request.email)
        console.log("   query_res is" , query_res)
        let uniqueId = query_res;
        if(query_res == null){
            uniqueId = uuidv4();
            uniqueId = shortenUUID(uniqueId);
            let bres = await redis_module.SetRedisExpire(const_module.code_prefix + call.request.email, uniqueId, 600)
            if(!bres){
                callback(null, {email: call.request.email,
                     error: const_module.Errors.RedisErr
                });
                return;
            }
        }

        console.log("   uniqueId is:", uniqueId)
        let text_str = `尊敬的用户：

您好！

您正在进行重要的注册流程。您的验证码为${uniqueId}。请务必在三分钟内完成注册，以确保您的操作顺利进行。

验证码是您注册过程中的重要凭证，请妥善保管，不要泄露给他人呜呜呜。

不是老弟你能反应我都变脸吗？码都不想要就直说！
`;
        //发送邮件
        let mailOptions = {
            from: '2105585205@qq.com',
            to: call.request.email,
            subject: '验证码_TEST',
            text: text_str,
        };

        let send_res = await emailModule.SendMail(mailOptions);

        // if(!send_res){//发送失败
        //     callback(null, {email: call.request.email,
        //         error: const_module.Errors.Exception
        //    });
        //    return;
        // }

        console.log("}\n")

        callback(null, { email:  call.request.email,
            error:const_module.Errors.Success
        }); 


    }catch(error){
        console.log("catch error is ", error)

        callback(null, { email:  call.request.email,
            error:const_module.Errors.Exception
        }); 
    }

}

function main() {
    var server = new grpc.Server()
    server.addService(message_proto.VerifyService.service, { GetVerifyCode: GetVerifyCode })
    server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => {
        server.start()
        console.log('verify server started')        
    })
}

main()